
#include "ApplyShaderToTexturedGeodeVisitor.h"

#include <osg/Geode>
#include <osg/Texture2D>
#include <assert.h>


CApplyShaderToTexturedGeodeVisitor::CApplyShaderToTexturedGeodeVisitor(osg::Program* shaderProgram, osg::NodeVisitor traversalMode) : osg::NodeVisitor(traversalMode)
{
	m_shader = shaderProgram;
}

void CApplyShaderToTexturedGeodeVisitor::apply(osg::Node& node)
{
	assert(m_shader.get());
	assert(&node);

	// cast node as geode
	osg::Geode* geode = node.asGeode();
	if(geode)
	{
		osg::StateSet* ss = geode->getStateSet();			
		if(ss)
		{
			// get texture
			osg::StateAttribute* texAttribute = ss->getTextureAttribute(0, osg::StateAttribute::TEXTURE);
			if(texAttribute)
			{
				osg::Texture2D* texture = dynamic_cast<osg::Texture2D*>(texAttribute);
				if(texture)
				{
					// add uniform attributs
					for(unsigned int i = 0; i < m_uniformList.size(); i++)
						ss->addUniform(m_uniformList[i]);

					// link shader and uniforms to material's node
					ss->setAttributeAndModes(m_shader.get(), osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
				}
			}
		}
	}

	traverse(node);
}